﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using Common;
using Panuon.UI.Silver;
using Panuon.UI.Silver.Core;
using Service.DtoModel;
using Service.DtoModel.DeskApp.pageModel;
using Service.Implements;

namespace RunApp.PartialViews.Business
{
    /// <summary>
    /// 菜品维护
    /// </summary>
    public partial class CaiPinWeiHu : UserControl
    {
        #region Property
        MenuService menuService = new MenuService();
        SysTypeService TypeService = new SysTypeService();
        #endregion

        public CaiPinWeiHu()
        {
            InitializeComponent();
            DataContext = this;
            dataList.MouseDown += DataGrid_MouseDown;
            GetTableList();
            GetTabTypeList();
        }

        #region Event
        /// <summary>
        /// 筛选菜品类别
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmbCustom_SearchTextChanged(object sender, Panuon.UI.Silver.Core.SearchTextChangedEventArgs e)
        {
            if (!IsLoaded) return;
            foreach (ComboBoxItem item in cmbTypes.Items)
            {
                item.Visibility = item.Content.ToString().Contains(e.Text) ? Visibility.Visible : Visibility.Collapsed;
            }
        }

        /// <summary>
        /// 全选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ckbSelectedAll_Checked(object sender, RoutedEventArgs e)
        {
            //this.dataList.SelectAll();
            for (int i = 0; i < this.dataList.Items.Count; i++)
            {
                var cntr = dataList.ItemContainerGenerator.ContainerFromIndex(i);
                DataGridRow ObjROw = (DataGridRow)cntr;
                if (ObjROw != null)
                {
                    FrameworkElement objElement = dataList.Columns[0].GetCellContent(ObjROw);
                    if (objElement != null)
                    {
                        //if (objElement.GetType().ToString().EndsWith("cRUID"))
                        //{
                        CheckBox objChk = (CheckBox)objElement;
                        if (objChk.IsChecked == false)
                        {
                            objChk.IsChecked = true;
                        }
                        //}
                    }
                }
            }
        }

        /// <summary>
        /// 全不选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ckbSelectedAll_Unchecked(object sender, RoutedEventArgs e)
        {
            this.dataList.UnselectAll();
            for (int i = 0; i < this.dataList.Items.Count; i++)
            {
                var cntr = dataList.ItemContainerGenerator.ContainerFromIndex(i);
                DataGridRow ObjROw = (DataGridRow)cntr;
                if (ObjROw != null)
                {
                    FrameworkElement objElement = dataList.Columns[0].GetCellContent(ObjROw);
                    if (objElement != null)
                    {
                        //if (objElement.GetType().ToString().EndsWith("cRUID"))
                        //{
                        CheckBox objChk = (CheckBox)objElement;
                        if (objChk.IsChecked == true)
                        {
                            objChk.IsChecked = false;
                        }
                        //}
                    }
                }
            }
        }
        /// <summary>
        /// 表格单行选中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataGrid_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                var selRow = dataList.SelectedItem;
                if (selRow != null)
                {
                    FrameworkElement objElement = dataList.Columns[0].GetCellContent(selRow);
                    if (objElement != null)
                    {
                        CheckBox objChk = (CheckBox)objElement;
                        objChk.IsChecked = !objChk.IsChecked;
                    }
                }
            }
        }
        /// <summary>
        /// 表格单行聚焦事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Item_GotFocus(object sender, RoutedEventArgs e)
        {
            var item = (DataGridRow)sender;
            FrameworkElement objElement = dataList.Columns[0].GetCellContent(item);
            if (objElement != null)
            {
                CheckBox objChk = (CheckBox)objElement;
                objChk.IsChecked = !objChk.IsChecked;
            }
        }
        /// <summary>
        /// “搜索”事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnSearch_Click(object sender, RoutedEventArgs e)
        {
            QueryData();
        }
        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefsh_Click(object sender, RoutedEventArgs e)
        {
            QueryData();
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAdd_Click(object sender, RoutedEventArgs e)
        {
            Window AddWin = new AddProWin();
            if (AddWin != null)
            {
                //(Application.Current.MainWindow as MainWindow).IsMaskVisible = true;
                AddWin.Closed += new EventHandler(RefshWin);//注册关闭事件
                AddWin.ShowDialog();
                //(Application.Current.MainWindow as MainWindow).IsMaskVisible = false;
            }
        }
        /// <summary>
        /// 停用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnStop_Click(object sender, RoutedEventArgs e)
        {

        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnDel_Click(object sender, RoutedEventArgs e)
        {
            var _selList = dataList.SelectedItems;
            var isSel = _selList.Count;
            if (isSel == 0)
            {
                MessageBoxX.Show("请选择要删除的数据.", "提示", Application.Current.MainWindow, MessageBoxButton.OK, new MessageBoxXConfigurations()
                {
                    MessageBoxIcon = MessageBoxIcon.Warning,
                    ButtonBrush = "#F1C825".ToColor().ToBrush(),
                });
                return;
            }
            var _msgRes = MessageBoxX.Show("确定要删除吗？", "提示", Application.Current.MainWindow, MessageBoxButton.YesNo, new MessageBoxXConfigurations()
            {
                MessageBoxIcon = MessageBoxIcon.Warning,
                ButtonBrush = "#F1C825".ToColor().ToBrush(),
            });
            if (_msgRes == MessageBoxResult.No) return;
            var _delIds = string.Empty;
            foreach (var item in _selList)
            {
                if (item != null)
                {
                    var _curObj = (ProDto)item;
                    if (!string.IsNullOrEmpty(_delIds)) _delIds += "," + _curObj.msId;
                    else _delIds = _curObj.msId.ToString();
                }
            }
            var _delRes = menuService.DeleteAsync(_delIds).Result;
        }
        /// <summary>
        /// 分页事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TabPagination_CurrentIndexChanged(object sender, Panuon.UI.Silver.Core.CurrentIndexChangedEventArgs e)
        {
            var _keyWhere = keyWhere.Text.Trim();
            GetTableList(_keyWhere);
        }
        private void RefshWin(object sender, EventArgs e)
        {
            QueryData();
        }
        #endregion

        #region Function
        /// <summary>
        /// 获取菜品列表
        /// </summary>
        public void GetTableList(string strWhere = "", string _rtId = "")
        {
            try
            {
                var _typeId = 0; int.TryParse(_rtId, out _typeId);
                var _pagesize = 10; int.TryParse(txtPageSize.Text.Trim(), out _pagesize);
                if (_pagesize <= 0) _pagesize = 13;
                var _parms = new PageParm { page = tabPagination.CurrentIndex, limit = _pagesize, key = strWhere, types = _typeId };
                var _pageRes = menuService.GetPagesAsync(_parms).Result;
                if (_pageRes.statusCode == (int)ApiEnum.Status)
                {
                    var _pageResData = _pageRes.data;
                    var _tabList = _pageResData.Items;
                    if (_tabList != null)
                    {
                        ObservableCollection<ProDto> tableDataList = new ObservableCollection<ProDto>();
                        foreach (var item in _tabList)
                        {
                            var _rtres = TypeService.GetModelAsync(" typeId='" + item.mtId + "' ").Result;
                            if (_rtres.statusCode == (int)ApiEnum.Status)
                            {
                                var _tName = _rtres.data != null ? _rtres.data.typeName : "";
                                var _curTab = new ProDto
                                {
                                    msId = item.msId,
                                    msName = item.msName,
                                    msUnit = item.msUnit,
                                    msPrice = item.msPrice,
                                    msScalar = item.msScalar,
                                    msCost = item.msCost,
                                    stId = item.stId,
                                    mtId = item.mtId,
                                    mtName = _tName
                                };
                                tableDataList.Add(_curTab);
                            }
                        }
                        dataList.DataContext = tableDataList;
                        txtTotalNum.Content = (int)_pageResData.TotalItems;
                        tabPagination.CurrentIndex = (int)_pageResData.CurrentPage;
                        tabPagination.TotalIndex = (int)_pageResData.TotalPages;
                    }
                    else
                    {
                        Notice.Show("没有获取到菜品数据！", "提示", 3, MessageBoxIcon.Info);
                        Logger.Default.ProcessError((int)ApiEnum.Error, "没有获取到菜品列表数据");
                    }
                }
                else
                {
                    Notice.Show("没有获取到菜品数据！", "提示", 3, MessageBoxIcon.Info);
                    Logger.Default.ProcessError(_pageRes.statusCode, "获取到菜品列表数据异常");
                }
            }
            catch (Exception ex)
            {
                Logger.Default.Error("获取菜品列表出现异常", ex);
            }
        }
        /// <summary>
        /// 获取菜品类别集合
        /// </summary>
        private void GetTabTypeList()
        {
            var _res = TypeService.GetListAsync().Result;
            if (_res.statusCode == (int)ApiEnum.Status)
            {
                List<ComboBoxItem> tabTypeList = new List<ComboBoxItem>();
                var _tabTypes = _res.data;
                var defObj = new ComboBoxItem
                {
                    Tag = "0",
                    Content = "请选择菜品类型"
                };
                tabTypeList.Add(defObj);
                foreach (var item in _tabTypes)
                {
                    var curObj = new ComboBoxItem
                    {
                        Tag = item.typeId,
                        Content = item.typeName
                    };
                    tabTypeList.Add(curObj);
                }
                cmbTypes.SelectedIndex = 0;
                cmbTypes.ItemsSource = tabTypeList;
            }
        }
        /// <summary>
        /// 获取并选中DependencyObject中的CheckBox
        /// </summary>
        /// <param name="parent"></param>
        public void GetVisualChild(DependencyObject parent)
        {
            int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < numVisuals; i++)
            {
                DependencyObject v = (DependencyObject)VisualTreeHelper.GetChild(parent, i);
                CheckBox child = v as CheckBox;
                if (child == null)
                {
                    GetVisualChild(v);
                }
                else
                {
                    child.IsChecked = true;
                    return;
                }
            }
        }
        /// <summary>
        /// 查询加载数据
        /// </summary>
        public void QueryData()
        {
            var _rtId = string.Empty;
            var _keyWhere = keyWhere.Text.Trim();
            var _selItem = cmbTypes.SelectedItem;
            if (_selItem is ComboBoxItem)
            {
                var __cmbItemobj = (ComboBoxItem)_selItem;
                _rtId = __cmbItemobj.Tag.ToString();
            }
            GetTableList(_keyWhere, _rtId);
        }
        #endregion        
    }
}
